/*
 *  @author zhangqiang
 *  @data 2017/03/14
 *   添加地址

 * karin 修改 2017/07/14
 * */
/**
 * Karin on 20170720
 * 年检支付后，编辑/新增用户地址
 */
import React, {Component} from 'react'
import {List, InputItem, Picker, TextareaItem, Toast, Button} from 'antd-mobile'
import {createForm} from 'rc-form'
import Style from './index.scss'
import 'style/addAddress.scss'
import getDataService from '../../services/getData'
import AlipayJSOperation from '../../utils/alipayJSOperation'
import NotExpression from '../../utils/expression'
import PageBar from '../../components/common/pageBar'
import ReModal from '../../components/common/reModal'
import BackMeanSure from '../../utils/backMeanSure';
import SendCxytjMessage from '../../utils/sendCxytjMessage';

class ProceDures extends Component {
    constructor(props) {
        super(props);

        this.state = {
            name: '',//姓名
            phone: '',//手机号
            details: '',//地址详情
            region: '',//地区
            focused: false,
            regionData: [], //后台获取地区信息
            dialogExist: false,//当前是否有弹框出现
        };
        this.orderId = this.props.params.orderId; // carId
        this.payTypeData = this.props.params.type; // 默认寄送类型.person个人；ems邮政
        this.backMeanSureInstance = new BackMeanSure(this.showMeansureBox, 'address');
    }

    /*	//清除ant弹框
     closeAliModal() {
     let div = document.querySelector(".am-modal-wrap");
     if (div) {
     div = div.parentNode;
     if (div) {
     div.parentNode.removeChild(div);
     }
     }
     }*/

    //姓名
    getName(e) {
        this.setState({name: e,});
        SendCxytjMessage.sendMessage({ eventId: 'H5_E_Addresspage_Inputname' });
    }

    //手机号
    getPhone(e) {
        this.setState({phone: e,});
        SendCxytjMessage.sendMessage({ eventId: 'H5_E_Addresspage_InputPhonenumber' });
    }

    //地区下拉列表
    getRegion(e) {
        this.setState({region: e,});
        SendCxytjMessage.sendMessage({ eventId: 'H5_E_Addresspage_ClickArea' });
    }

    getDetails(e) {//地址详情
        this.setState({details: e,})
        SendCxytjMessage.sendMessage({ eventId: 'H5_E_Addresspage_InputDetailedaddress' });
    }



    subMit() {//提交表单
        let that = this.state;
        let self=this;
        this.props.form.validateFields((error, value) => {
            let telNum = that.phone.replace(/\s+/g, ""),
                reg = /^0?1[3|4|5|7丨8][0-9]\d{8}$/,
                reg_name = /^[a-zA-Z\u4e00-\u9fa5\s]{1,20}$/;
            if (!that.name && !that.phone && !value.district && !value.focus) {
                Toast.info('请填写资料!', 1);
                return false;
            } else {
                if (that.name == '' || !that.name || that.name.replace(/(^\s*)|(\s*$)/g, "") == "") {
                    Toast.info('姓名不能为空!', 1);
                    return false;
                } else if (!reg_name.test(that.name)) {
                    Toast.info('姓名格式错误', 1)
                    return false;
                } else if (NotExpression.isEmojiCharacter(that.name.toString())) {
                    Toast.info('姓名不能包含表情!', 1);
                    return false;
                } else if (that.phone == '' || !that.phone) {
                    Toast.info('手机号码不能为空!', 1);
                    return false;
                } else if (!reg.test(telNum)) {
                    Toast.info('手机格式错误!', 1)
                    return false;
                } else if (!value.district) {
                    Toast.info('请填写省，市，区(县)!', 1);
                    return false;
                } else if (value.note1 == '' || !value.note1 || value.note1.replace(/(^\s*)|(\s*$)/g, "") == "") {
                    Toast.info('请填写详细地址!', 1);
                    return false;
                }else if (NotExpression.isEmojiCharacter(value.note1)) {
                    Toast.info('详细地址不能包含表情!', 1);
                    return false;
                } else if (value.note1.toString().length < 5) {
                    Toast.info('详细地址长度应不少于5位!', 1);
                    return false;
                }
            }

            let postData = {
                name: that.name,
                phone: that.phone,

                provinceCode: value.district[0] ? value.district[0].split(',')[1] : this.state.provinceCode, //省份code
                provinceName: value.district[0] ? value.district[0].split(',')[0] : this.state.provinceName, //省份
                cityCode: value.district[1] ? value.district[1].split(',')[1] : this.state.cityCode,//城市code
                cityName: value.district[1] ? value.district[1].split(',')[0] : this.state.cityName,//城市
                areaCode: value.district[2] ? value.district[2].split(',')[1] : null,//所在区code
                areaName: value.district[2] ? value.district[2].split(',')[0] : null,//所在区

                location: value.note1,
            };

            Toast.hide(); //加载前 先关闭其他加载中的提示框 避免提示框一直存在的bug
            Toast.loading("", 30, () => Toast.info("网络错误", 2));
            getDataService.addAddressManually(postData).then(data => {
                Toast.hide();
                if (data.code == 1000) {
                    Toast.info('保存成功', 1);
                    localStorage.removeItem('addressList_action');
                    setTimeout(()=>{self.backMeanSureInstance.back()}, 300)
                } else {
                    Toast.info(data.msg);
                }
            })
        });
        SendCxytjMessage.sendMessage({ eventId: 'H5_E_Addresspage_ClickSaveaddress' });
    }


/*    setUrlBack(e) {
        if (location.href.indexOf('addAddress') > -1) {
            this.sendMessage('insepection_addaddress_back');
            if (e) {
                e.preventDefault();
            }

            if (this.state.name || this.state.phone || this.state.details.length || this.state.region) {
                ReModal.confirm('编辑的信息还未保存，确认现在返回吗？', () => {
                    history.go(-1)
                });

            } else {
                history.go(-1)
            }
        }
    }*/

    /**
     * 生命周期
     */
    componentWillMount() {

    }

    //弹出未保存提示框
    showMeansureBox(back, stay) {
        ReModal.confirm('编辑的信息还未保存，确定现在返回吗？', () => {
            back();
        }, () => {
            stay();
        });
    }

    componentDidMount() {
        this.backMeanSureInstance.bindBackMeansure();
        document.querySelector("title").innerHTML = "添加地址";
        //隐藏标题栏右键
        AlipayJSOperation.setRightButtonStatus(false);
        //设置标题
        AlipayJSOperation.setTitle('添加地址');
        //设置标题颜色
        AlipayJSOperation.setBarColor('#2FB3FE');

        getDataService.regionate('').then(data => { //省，市，区
            Toast.hide();
            // Toast.loading("",0)
            if (data.code == 1000) {
                this.setState({
                    regionData: data.data.value,
                })
            } else {
                Toast.info(data.msg);
            }
        })

        let postData = {
            orderId: this.orderId
        }

        Toast.hide(); //加载前 先关闭其他加载中的提示框 避免提示框一直存在的bug
        Toast.loading("", 30, () => Toast.info("网络错误", 2));
        getDataService.getInfo(postData).then(resultData => { //省，市，区
            Toast.hide();
            // Toast.loading("",0)
            console.log(resultData)
            if (resultData.code == 1000) {
                this.setState({
                    name: resultData.data.name,//姓名
                    phone: resultData.data.phone,//手机号
                })
            } else {
                Toast.info(resultData.msg);
            }
        })

        //AlipayJSOperation.setLeftButtonStatus(this.setUrlBack)
        SendCxytjMessage.sendMessage({ eventId: 'H5_P_Interspection_EnterAddresspage' });
    }

    componentDidUpdate() {
    }


    componentWillUnmount() {
        AlipayJSOperation.removeLeftButtonEvent();
    }

    render() {
        var me = this;
        const {getFieldProps} = this.props.form

        return (
            <div>
                <div className={Style.proceDures + ' proceDures'}>
                    <PageBar title="添加地址"/>
                    
                    <InputItem
                        style={{width: '100%', color: '#108ee9', textAlign: 'right',marginTop:'12px'}}
                        {...getFieldProps('name') }
                        //clear    清除叉叉
                        placeholder="请输入姓名"
                        maxLength="12"
                        autoFocus
                        value={this.state.name}
                        onBlur={(e) => {
                            this.getName(e)
                        }}
                        onChange={(name) => this.setState({name})}
                    >姓名</InputItem>

                    <InputItem
                        {...getFieldProps('phone') }
                        type="number"  //phone
                        maxLength="11"
                        placeholder="请输入手机号码"
                        value={this.state.phone}
                        onBlur={(e) => {
                            this.getPhone(e)
                        }}
                        onChange={(phone) => this.setState({phone})}
                    >联系电话</InputItem>

                    <List style={{backgroundColor: 'white'}} className="picker-list">

                        <Picker extra="请选择" data={this.state.regionData}
                                format={(values) => {
                                    {
                                        return values.join('');
                                    }
                                }}
                                title="选择地区" {...getFieldProps('district', {
                            onChange(e) {
                                me.getRegion(e)
                                let extra = document.getElementsByClassName('am-list-extra').innerHTML;
                            },
                        }) }
                        >
                            <List.Item arrow="horizontal">所在地区</List.Item>
                        </Picker>
                        <TextareaItem
                            {...getFieldProps('note1') }
                            rows={4}
                            onBlur={(e) => {
                                this.getDetails(e)
                            }}
                            placeholder="请填写详细地址"
                            maxLength="60"
                        />
                    </List>
                </div>

                {this.payTypeData == 'ems' &&<div className=' color999 plr30 pt30 font-26 text-center'>
					<span className={Style.iconI}>您选择的邮政上门取件，仅支持广东省内地址</span>
				</div>}

                <Button className={Style.fixedBtn} type="primary" size={'default'}
                        onClick={e => this.subMit()}>保存地址</Button>
            </div>
        )
    }
}

ProceDures.contextTypes = {
    router: React.PropTypes.object.isRequired
};

ProceDures.defaultProps = {}

export default createForm()(ProceDures);
